﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Finance.Basedatas;
using mozhi.smarterp.Finance.Basedatas.Repository;
using mozhi.smarterp.Finance.EntityFrameworkCore;
using mozhi.smarterp.Finance.Querys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.Finance.Tags
{
    public class TagRepository : BaseDataRepository<Tag>, ITagRepository
    {
        public TagRepository(IDbContextProvider<FinanceDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public override Task<List<Tag>> FindAsync(PageQuery query)
        {
            var dbQuery = query.IncludeDetail ? DbContext.Set<Tag>().Include(x => x.Items).AsNoTracking() : DbContext.Set<Tag>().AsNoTracking();

            var entities = dbQuery
                 .WhereIf(!query.Keyword.IsNullOrEmpty(), x => x.Name.Contains(query.Keyword))
                 .WhereIf(query.Ids != null && query.Ids.Count > 0, x => query.Ids.Contains(x.Id))
                 .WhereIf(query.Activated.HasValue, x => x.Activated == query.Activated.Value)
                 .WhereIf(query.ExclusionId.HasValue, x => x.Id != query.ExclusionId.Value)
                 .Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize)
                 .ToListAsync();

            return entities;
        }

        public override async Task<Tag> GetAsync(Guid id, bool includeDetails = true, CancellationToken cancellationToken = default)
        {
            var tag = await DbContext.Set<Tag>().Include(x => x.Items).FirstOrDefaultAsync(x => x.Id == id);

            return tag;
        }

        public override async Task<Tag> FindAsync(Guid id)
        {
            var tag = await DbContext.Set<Tag>().Include(x => x.Items).AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);

            return tag;
        }


        public async Task<List<TagItem>> FindItemsAsync(Guid tagId, PageQuery query)
        {
            var dbQuery = DbContext.Set<TagItem>().AsNoTracking().Where(x=>x.TagId == tagId);

            var entities = await dbQuery
                 .WhereIf(!query.Keyword.IsNullOrEmpty(), x => x.Name.Contains(query.Keyword))
                 .WhereIf(query.Ids != null && query.Ids.Count > 0, x => query.Ids.Contains(x.Id))
                 .WhereIf(query.Activated.HasValue, x => x.Activated == query.Activated.Value)
                 .WhereIf(query.ExclusionId.HasValue, x => x.Id != query.ExclusionId.Value)
                 .Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize)
                 .ToListAsync();

            return entities;
        }
    }
}
